<?php
namespace app\admin\model;
use think\Model;
use app\admin\model\SystemUpload;


class SystemParamValue extends Model {
	
	//主键		
	protected $pk = 'id';
	// 自动完成, 只在新增的时候有效
	protected $insert = ['sort_no'];
	protected function setSortNoAttr() {
		if(!empty($this->param_code)){
			$result = $this  
        		->where("param_code",$this->param_code) 
        		->where("param_scope",$this->param_scope)
				->max('sort_no');
			return 	$result + 1;
		}
    }
   
	//获取参数值
	public function getTextParamValue($param_scope,$param_code){
		$model = $this->where("param_code",$param_code)->where("param_scope",$param_scope);
		if( ($shop_id =  request()->get('shop_id','')) || $shop_id === '0' ){
			$model = $model->where("parent_value",$shop_id);
		}
		return $model->value('param_value');	
	}
	
	//保存文本参数
	public function saveTextParamValue($data){
		$param["param_code"] = $data['param_code'];
		$param['param_scope'] = $data['param_scope'];
		if( ($shop_id =  request()->get('shop_id','')) || $shop_id === '0' ){
			$data['parent_value'] = $param['parent_value'] = $shop_id;
		}
		$data['id'] = $this -> where($param) ->value('id');
		$this->where('id',$data['id'])->delete();
		return $this->save($data) ? 1 : 0;
	}
	
	//保存参数
	public function saveParam($data){
		if($data['id']){
			$this ->where('id',$data['id'])->update($data);
		}else{
			$this -> save($data);
		}
		return true;
	}
	
	//获取参数
	public function getParams($param_scope,$param_code){
		$param['param_scope'] = $param_scope;
		$param["param_code"] = $param_code;
		return $this->where($param)->order('sort_no asc')->select();
	}
	
	//更新排序 
	public function updateSort($moveId,$coverId){
		$sort_no = $this->where('id',$coverId)->value('sort_no');
		$sort_no2 = $this->where('id',$moveId)->value('sort_no');
		$rerult = $this->where('id',$moveId)->update( [ 'sort_no'=> $sort_no ]);
		$rerult = $this->where('id',$coverId)->update( [ 'sort_no'=> $sort_no2 ]);
		return $rerult;
	}


	//获取下拉参数
	public function getSelectParams($param_scope,$param_code){
		$model = new self;
		$model = $model->where('param_scope',$param_scope);
		$model = $model->where('param_code',$param_code);
		$model = $model->field('param_value as value');
		$model = $model->field('param_text as label');
		$model = $model->order('sort_no asc');
		return $model->select();
	}
	
	//获取轮播图
	public function getSlides($paramCode,$fileGuid){
		return SystemUpload::getSlides($paramCode,$fileGuid);
	}
	
}